package org.ihelpuoo.weboo.upload.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.ihelpuoo.filepool.TempFilePool;
import org.ihelpuoo.http.HTTP;
import org.ihelpuoo.lang.ExceptionUtils;
import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.lang.NutException;
import org.ihelpuoo.parser.segment.CharSegment;
import org.ihelpuoo.parser.segment.Segment;
import org.ihelpuoo.util.Properties;
import org.ihelpuoo.weboo.action.http.Action;
import org.ihelpuoo.weboo.module.ActionConfig;
import org.ihelpuoo.weboo.module.ActionContext;
import org.ihelpuoo.weboo.module.ModuleContext;
import org.ihelpuoo.weboo.upload.FieldsLoader;

public abstract class FileUploadAction implements Action
{
	private Logger			log;
	private TempFilePool	tempFilePool;

	public FileUploadAction()
	{
		log = Logger.getLogger(this.getClass());
	}

	public void execute(ActionContext context)
	{
		String contentType = context.getRequest().getContentType();
		String boundary = HTTP.formatMultipartBoundary(HTTP
				.retrieveMultipartRequestBoundary(contentType));
		InputStream ins = null;
		try
		{
			ins = context.getRequest().getInputStream();
			BoundaryLoader bl = new BoundaryLoader(boundary);
			bl.parse(ins);
			Map<String, Object> params = new HashMap<String, Object>();
			initTempFilePool(context.getModuleContext(),context.getActionConfig(),context
					.getRequest());
			FieldsLoader fields = new FieldsLoader(boundary,params,tempFilePool);
			fields.parse(ins);
			ins.close();
			ins = null;
			execute(context,params);
		}
		catch (Exception e)
		{
			log.warn(ExceptionUtils.dump(e));
		}
		finally
		{
			if (null != ins)
				try
				{
					ins.close();
				}
				catch (IOException e)
				{
					log.warn(ExceptionUtils.dump(e));
				}
		}

	}

	private void initTempFilePool(ModuleContext context, ActionConfig config,
			HttpServletRequest request) throws NutException, LoaderException
	{
		if (null == tempFilePool)
		{
			synchronized (this)
			{
				if (null == tempFilePool)
				{
					String name = config.getPropertyValue(context.getConfig().getStringTrimed(
							"TEMP_POOL_NAME"));
					Properties p = context.nut().getConfig(name);
					Segment seg = new CharSegment(p.getStringTrimed("home"));
					seg.set("appRoot",request.getSession().getServletContext().getRealPath("/"));
					p.setProperty("home",seg.toString());
					tempFilePool = (TempFilePool)context.nut().getFactory(p);
				}
			}
		}
	}

	protected abstract void execute(ActionContext context, Map<String, Object> params);

}
